package com.unidt.www.module.third.enterprise.service.impl;


import cn.hutool.json.JSONObject;
import com.unidt.www.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.unidt.www.framework.common.pojo.CommonResult;
import com.unidt.www.framework.common.pojo.PageResult;
import com.unidt.www.framework.common.util.http.OkHttpUtils;
import com.unidt.www.framework.common.util.object.BeanNullUtil;
import com.unidt.www.module.system.controller.admin.auth.vo.AuthLoginReqVO;
import com.unidt.www.module.system.controller.admin.auth.vo.AuthLoginRespVO;
import com.unidt.www.module.system.controller.admin.user.vo.user.UserCreateReqVO;
import com.unidt.www.module.system.dal.dataobject.user.AdminUserDO;
import com.unidt.www.module.system.service.auth.AdminAuthService;
import com.unidt.www.module.system.service.permission.PermissionService;
import com.unidt.www.module.system.service.user.AdminUserService;
import com.unidt.www.module.third.enterprise.dao.EnterpriseNoticeMapper;
import com.unidt.www.module.third.enterprise.domain.EnterpriseNoticeDO;
import com.unidt.www.module.third.enterprise.domain.SystemUserEnterpriseDO;
import com.unidt.www.module.third.enterprise.service.EnterpriseNoticeService;
import com.unidt.www.module.third.enterprise.service.SystemUserEnterpriseService;
import com.unidt.www.module.third.enterprise.vo.notice.EnterpriseNoticeCreatReqVO;
import com.unidt.www.module.third.enterprise.vo.notice.EnterpriseNoticeListReqVO;
import com.unidt.www.module.third.enterprise.vo.notice.EnterpriseNoticeUpdateReqVO;
import com.unidt.www.module.third.enterprise.vo.system.SystemUserEnterpriseCreatReqVO;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * <p>
 * 部门表 服务实现类
 * </p>
 *
 * @author ouyangoyys
 * @since 2022-11-24
 */
@Service
@Log4j2
public class EnterpriseNoticeServiceImpl implements EnterpriseNoticeService {


    @Resource
    AdminUserService adminUserService;


    @Resource
    private AdminAuthService authService;

    @Resource
    private PermissionService permissionService;


    @Resource
    private EnterpriseNoticeMapper enterpriseMapper;


    @Resource
    private SystemUserEnterpriseService systemUserEnterpriseService;


    /**
     *
     * 1、请求https://zj87.jxt.zj.gov.cn/webapi/cust/getToken获取token返回值。
     * jlbtoken
     * 2、https://zj87.jxt.zj.gov.cn/webapi/cust/isLogin?jlbtoken=XXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXXXXXX
     *
     * @param
     * @return
     */
    @Override
    public CommonResult<AuthLoginRespVO> getEnterpriseTokenByUserInfo(String token) {

//        String tokenJson=OkHttpUtils.builder()
//                .url("https://zj87.jxt.zj.gov.cn/webapi/cust/getToken")
//                .get();
//        JSONObject mJSONObject = new JSONObject(tokenJson);
//        JSONObject mBodyJson= (JSONObject) mJSONObject.get("body");
//        String token= (String) mBodyJson.get("jlbtoken");

        if(StringUtils.isBlank(token)){
            return CommonResult.error(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"token：null");
        }

        log.info("qym-token:"+token);

        String resp=OkHttpUtils.builder()
                .url("https://zj87.jxt.zj.gov.cn/webapi/cust/isLogin?jlbtoken="+token)
                .get();
        if(StringUtils.isBlank(resp)){
            return CommonResult.error(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"企业码接口有错！");
        }

        log.info("qym-token-info:"+resp);


//        try {
            JSONObject respJson = new JSONObject(resp);
            JSONObject mUserInfo= (JSONObject) respJson.get("body");
            boolean isLogin= (boolean) mUserInfo.get("isLogin");
            if(isLogin) {
                String mobile= (String) mUserInfo.get("MOBILE");
                String loginName= (String) mUserInfo.get("MOBILE");
                String nickName= (String) mUserInfo.get("CUSTNAME");

                AdminUserDO mAdminUserDO = adminUserService.getUserByMobile(mobile);


                /**
                 * 创建一个自己用户
                 */
                if(mAdminUserDO==null) {
                    UserCreateReqVO mUserCreateReqVO = new UserCreateReqVO();
                    mUserCreateReqVO.setMobile(mobile);
                    mUserCreateReqVO.setUsername(mobile);
                    mUserCreateReqVO.setPassword("Qq123456");
                    mUserCreateReqVO.setNickname(nickName);
                    mUserCreateReqVO.setUserType(3);
                    mUserCreateReqVO.setDeptId(2000L);
                    mUserCreateReqVO.setTenantId(1L);
                    adminUserService.createUser(mUserCreateReqVO);

                }

                /**
                 * 写死企业码的角色
                 */
                mAdminUserDO= adminUserService.getUserByMobile(mobile);
                Set<Long> set=new HashSet<>();
                set.add(118L);
                log.info("qym:"+permissionService.hasAnyRoles(mAdminUserDO.getId(),"qym"));
                if(!permissionService.hasAnyRoles(mAdminUserDO.getId(),"qym")) {
                    permissionService.assignUserRole(mAdminUserDO.getId(), set);
                }

                /**
                 * 免登
                 */
                AuthLoginRespVO mAuthLogin = authService.loginNoPassWord(new AuthLoginReqVO()
                        .setUsername(loginName));

                /**
                 * 创建企业信息
                 */

            try{
                SystemUserEnterpriseDO  mSystemUserEnterpriseDO=systemUserEnterpriseService.selectByUserId(mAuthLogin.getUserId());
             if(mSystemUserEnterpriseDO==null) {
                 String respDetail = OkHttpUtils.builder()
                         .url("https://zj87.jxt.zj.gov.cn/webapi/cust/getDetail?ID=" + mUserInfo.get("CUSTID") + "&jlbtoken=" + token)
                         .get();

                 log.info("qym-token-respDetail:" + respDetail);

                 JSONObject detailJson = new JSONObject(respDetail);
                 JSONObject detail = (JSONObject) detailJson.get("body");

                 SystemUserEnterpriseCreatReqVO mSystemUserEnterpriseCreatReqVO = new SystemUserEnterpriseCreatReqVO();
                 mSystemUserEnterpriseCreatReqVO.setUserId(mAuthLogin.getUserId());
                 mSystemUserEnterpriseCreatReqVO.setRegcode((String) mUserInfo.get("REGCODE"));
                 mSystemUserEnterpriseCreatReqVO.setAcctname((String) mUserInfo.get("ACCTNAME"));
                 mSystemUserEnterpriseCreatReqVO.setCustname((String) mUserInfo.get("CUSTNAME"));
                 mSystemUserEnterpriseCreatReqVO.setOfficetel((String) mUserInfo.get("OFFICETEL"));
                 mSystemUserEnterpriseCreatReqVO.setCountyid(String.valueOf(mUserInfo.get("COUNTYID")));
                 mSystemUserEnterpriseCreatReqVO.setProvinceid(String.valueOf(mUserInfo.get("PROVINCEID")));

                 /**
                  * 企业码新接口
                  */
                 mSystemUserEnterpriseCreatReqVO.setType("");//企业类型
                 mSystemUserEnterpriseCreatReqVO.setTrade("");//企业行业
                 mSystemUserEnterpriseCreatReqVO.setCustDesc((String) detail.get("CUST_DESC"));
                 systemUserEnterpriseService.create(mSystemUserEnterpriseCreatReqVO);
                    }
                }catch (Exception e){

                            log.info("qym:企业信息接口解析报错。");

                        }



                return CommonResult.success(mAuthLogin);
            }
            return CommonResult.error(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"isLogin："+isLogin);

//        }

//        catch (Exception e){
//            return CommonResult.error(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"token解析出错！");
//
//        }
    }

    @Override
    public CommonResult<AuthLoginRespVO> getClientUserTokenByUserInfo(String token) {
        return CommonResult.success(null);
    }

    @Override
    public Long createEnterprise(EnterpriseNoticeCreatReqVO reqVO) {

        EnterpriseNoticeDO mEnterpriseDO=new EnterpriseNoticeDO();
        BeanUtils.copyProperties(reqVO,mEnterpriseDO);
        enterpriseMapper.insert(mEnterpriseDO);

        return mEnterpriseDO.getId();
    }

    @Override
    public void updateEnterprise(EnterpriseNoticeUpdateReqVO reqVO) {

        EnterpriseNoticeDO mEnterpriseDO =enterpriseMapper.selectById(reqVO.getId());
        if(mEnterpriseDO!=null){
            BeanUtils.copyProperties(reqVO, mEnterpriseDO, BeanNullUtil.getNullPropertyNames(reqVO));
            enterpriseMapper.updateById(mEnterpriseDO);
        }

    }

    @Override
    public void deleteEnterprise(Long id) {
        enterpriseMapper.deleteById(id);
    }

    @Override
    public PageResult<EnterpriseNoticeDO> getSimpleEnterprise(EnterpriseNoticeListReqVO reqVO) {

        return enterpriseMapper.selectList(reqVO);
    }
}
